package com.nfu.zlsp.dev.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nfu.zlsp.dev.common.utils.PageUtils;
import com.nfu.zlsp.dev.common.utils.Query;
import com.nfu.zlsp.dev.dao.AddressDao;
import com.nfu.zlsp.dev.dao.ConsignDao;
import com.nfu.zlsp.dev.dao.UserDao;
import com.nfu.zlsp.dev.entity.AddressEntity;
import com.nfu.zlsp.dev.entity.ConsignEntity;
import com.nfu.zlsp.dev.entity.TransportEntity;
import com.nfu.zlsp.dev.entity.UserEntity;
import com.nfu.zlsp.dev.entity.vo.QueryConsignVo;
import com.nfu.zlsp.dev.entity.vo.QueryTransportVo;
import com.nfu.zlsp.dev.service.AddressService;
import com.nfu.zlsp.dev.service.ConsignService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("consignService")
public class ConsignServiceImpl extends ServiceImpl<ConsignDao, ConsignEntity> implements ConsignService {

    @Autowired
    private AddressService addressService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private AddressDao addressDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ConsignEntity> page = this.page(
                new Query<ConsignEntity>().getPage(params),
                new QueryWrapper<ConsignEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryMyConsignPage(UserEntity user) {


        QueryWrapper<ConsignEntity> queryWrapper = new QueryWrapper<>();
        Map<String,Object> map = new HashMap<>();
        map.put("state","0");
        //查询 ”我的“  "未接单"
        queryWrapper.eq("state","0").eq("c_userid",user.getId());
        IPage<ConsignEntity> page = this.page(
                new Query<ConsignEntity>().getPage(map),
                queryWrapper
        );

        List<ConsignEntity> consignEntityList = page.getRecords();

        //根据地区编号查赋予细地址
        List<ConsignEntity> collect = consignEntityList.stream().map(consignEntity -> {
            String pickAddress = addressService.getAddressByRegionId(consignEntity.getPickupAddress());
            String unloadAddress = addressService.getAddressByRegionId(consignEntity.getUnloadAddress());
            pickAddress += consignEntity.getPickupDetailAddress();
            unloadAddress += consignEntity.getUnloadDetailAddress();
            consignEntity.setPickupDetailAddress(pickAddress);
            consignEntity.setUnloadDetailAddress(unloadAddress);
            return consignEntity;
        }).collect(Collectors.toList());


        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(consignEntityList);
        return  pageUtils;

    }

    @Override
    public void cancelConsignById(String id) {
        this.baseMapper.deleteById(id);
    }

    @Override
    public PageUtils queryConsignPageByInfo(Map<String, Object> params) {



        QueryWrapper<ConsignEntity> queryWrapper = new QueryWrapper<>();
        String logisticsType = (String) params.get("logisticsType");
        String transportMode = (String) params.get("transportMode");
        String minPrice = (String) params.get("minPrice");
        String maxPrice = (String) params.get("maxPrice");
        String volume = (String) params.get("volume");
        String weight = (String) params.get("weight");
        String pickupTime = (String) params.get("pickupTime");
        String pickUpCity = (String) params.get("pickUpCity");
        String unloadCity = (String) params.get("unloadCity");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        if(minPrice == null){
            queryWrapper.eq("state","0");
        }else{
            queryWrapper.eq("logistics_type",logisticsType).eq("transport_mode",transportMode).eq("state","0");
            queryWrapper.between("price",minPrice,maxPrice);
            queryWrapper.gt("pickup_Time",pickupTime);
            if (volume != "" ) {
                queryWrapper.eq("volume",volume);
            }
            if (weight != ""){
                queryWrapper.eq("weight",weight);
            }
        }




        IPage<ConsignEntity> page = this.page(
                new Query<ConsignEntity>().getPage(params),
                queryWrapper
        );

        List<ConsignEntity> consignEntityList = page.getRecords();

        long t1 = 0;
        long t2 = 0;



        List<QueryConsignVo> queryConsignVoList = consignEntityList.stream().map(consignEntity -> {
            QueryConsignVo queryConsignVo = new QueryConsignVo();
            BeanUtils.copyProperties(consignEntity, queryConsignVo);
            UserEntity userEntity = userDao.selectOne(new QueryWrapper<UserEntity>().eq("id", consignEntity.getCUserid()));

            //写入公司
            queryConsignVo.setCompany(userEntity.getCompany());
            queryConsignVo.setUsername(userEntity.getUsername());
            queryConsignVo.setNumber(userEntity.getNumber());
            queryConsignVo.setEmail(userEntity.getEmail());


            //写入时效
            Long time1 = null;
            try {
                time1 = sdf.parse(consignEntity.getDeliveryTime()).getTime();
                Long time2 = sdf.parse(consignEntity.getPickupTime()).getTime();
                queryConsignVo.setLimitTime((time1 - time2) / (1000 * 60 * 60));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //写出发地和目的地
            queryConsignVo.setBeginAddress(addressService.getAddressByRegionId(consignEntity.getPickupAddress()) + consignEntity.getPickupDetailAddress());
            queryConsignVo.setEndAddress(addressService.getAddressByRegionId(consignEntity.getUnloadAddress()) + consignEntity.getUnloadDetailAddress());

            /**
             * 删选出地址不符合查询条件的
             *  返回空的QueryTransportVo
             */

            if(minPrice != null){
                AddressEntity beginCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", consignEntity.getPickupAddress()));
                AddressEntity endCity = addressDao.selectOne(new QueryWrapper<AddressEntity>().eq("address_areaId", consignEntity.getUnloadAddress()));
                if (!(beginCity.getAddressRegionid().equals(pickUpCity) && endCity.getAddressRegionid().equals(unloadCity))) {
                    //地址条件不符
                    return new QueryConsignVo();
                }
            }

            return queryConsignVo;


        }).collect(Collectors.toList());

        //用迭代器删除值为空的元素（迭代器遍历不会报错 foreach会）
        Iterator iterator = queryConsignVoList.iterator();
        while (iterator.hasNext()){
            QueryConsignVo vo = (QueryConsignVo) iterator.next();
            if(vo.getId() == null){
                iterator.remove();
            }

        }

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(queryConsignVoList);

        return pageUtils;
    }


}


















